package com.ruoyi.project.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.ZeWuService;
import com.ruoyi.project.system.domain.DtFinalResult;
import com.ruoyi.project.system.domain.DtProduct;
import com.ruoyi.project.system.domain.DtQuery;
import com.ruoyi.project.system.domain.dto.Decision;
import com.ruoyi.project.system.domain.dto.QueryData;
import com.ruoyi.project.system.domain.dto.QueryDecision;
import com.ruoyi.project.system.domain.dto.TwoEleResult;
import com.ruoyi.project.system.domain.vo.QueryDataVo;
import com.ruoyi.project.system.domain.vo.QueryRecord;
import com.ruoyi.project.system.mapper.DtFinalResultMapper;
import com.ruoyi.project.system.mapper.DtProductMapper;
import com.ruoyi.project.system.mapper.DtQueryMapper;
import com.ruoyi.project.system.service.IDtFinalResultService;
import com.ruoyi.project.system.service.IDtQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.constant.CacheConstants.STREAM_REPORT;
import static com.ruoyi.common.constant.CacheConstants.STREAM_REPORT_TOKEN;
import static com.ruoyi.common.utils.CardNoUtils.getBirAgeSex;
import static com.ruoyi.common.utils.SMS.generatePhoneNumber;
import static com.ruoyi.common.utils.http.HttpUtils.dataPost;
import static com.ruoyi.framework.web.domain.AjaxResult.success;
import static com.ruoyi.framework.web.domain.AjaxResult.warn;

/**
 * 查询列表Service业务层处理
 */
@Service
public class DtQueryServiceImpl implements IDtQueryService {

    @Autowired
    private IDtFinalResultService iDtFinalResultService;

    @Autowired
    private ZeWuService zeWuService;

    @Autowired
    private DtQueryMapper dtQueryMapper;

    @Autowired
    private DtProductMapper dtProductMapper;

    @Autowired
    private DtFinalResultMapper dtFinalResultMapper;

    @Autowired
    private RedisCache rc;

    @Value("${back_url}")
    private String back_url;

    public int setQueryDecision(QueryDecision qd) {
        Integer id = dtQueryMapper.selectQueryDecision(qd);
        if (id == null) {
            return dtQueryMapper.insertQueryDecision(qd);
        }
        qd.setId(id);
        return dtQueryMapper.updateQueryDecision(qd);
    }

    @Override
    public List<QueryRecord> handlerQueryResult(List<QueryRecord> list) {
        for (QueryRecord qr : list) {
//            if (StringUtils.isNotEmpty(qr.getName())) {
//                qr.setName("**" + qr.getName().substring(1));
//            }
            if ("1".equals(qr.getVirtualTel())) {
                qr.setTel("*******" + qr.getTel().substring(7) + "（虚拟号码）");
            } else {
                qr.setTel("*******" + qr.getTel().substring(7));
            }
            List<Decision> decisions = dtQueryMapper.decisionItems(qr.getQueryId());
            String[] keys = {"thrEle", "score", "idea", "address", "constellation"};
            qr.setDecisions(new HashMap<>());
            boolean is;
            for (String key : keys) {
                is = false;
                for (Decision decision : decisions) {
                    if (key.equals(decision.getType())) {
                        qr.getDecisions().put(key, decision.getInfo());
                        is = true;
                        break;
                    }
                }
                if (!is) {
                    qr.getDecisions().put(key, "");
                }
            }
            qr.getDecisions().putAll(getBirAgeSex(qr.getCardNo()));

            qr.setCardNo("******" + qr.getCardNo().substring(6));
        }
        return list;
    }

    @Override
    public TwoEleResult verificationTwoEle(DtQuery query) {
        // MGZ TODO 2025/6/4: 进件二要素核查
        DtFinalResult dfr = iDtFinalResultService.feeDeduction(query.getUserId(), 1, null);
        TwoEleResult ter = null;
        try {
            QueryData queryData = generalQuery(dfr, query);
            if (queryData.isSuccess()) {
                JSONObject result = (JSONObject) queryData.getInfo();
                String final_auth_result = result.getString("final_auth_result");
                if ("0".equals(final_auth_result)) {
                    ter = new TwoEleResult(result);
                } else if ("1".equals(final_auth_result)) {
                    ter = new TwoEleResult("姓名，身份证不一致或不存在", result);
                } else {
                    ter = new TwoEleResult("校验异常", result);
                }
            } else {
                ter = new TwoEleResult(queryData.getMsg(), null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ter = new TwoEleResult(e.getMessage(), null);
        } finally {
            return ter;
        }
    }

    @Override
    public void ordinaryAddQuery(DtQuery dtQuery) {
        if (StringUtils.isEmpty(dtQuery.getTel())) {
            dtQuery.setTel(generatePhoneNumber());
            dtQuery.setVirtualTel("1");
        }
        dtQuery.setAuthCode(UUID.randomUUID().toString().substring(0, 8));
        dtQueryMapper.insertOrdinaryQuery(dtQuery);
    }

    @Override
    public AjaxResult fastQuery(DtFinalResult dfr) {
        DtQuery dtQuery = dtQueryMapper.selectDtQueryByQueryId(dfr.getQueryId());
        dfr.setUpdateTime(DateUtils.getNowDate());
        Integer productId = dfr.getProductId();
        QueryData queryData;
        // 分别查询
        if (productId == 2) {
            queryData = thrEleQuery(dfr, dtQuery);
        } else if (productId == 50) {
            queryData = streamReport(dfr, dtQuery);
        } else {
            queryData = generalQuery(dfr, dtQuery);
        }
        // 判别写入
        if (queryData.isSuccess()) {
            String tel = dtFinalResultMapper.selectQueryKeyword(dfr.getId(), productId, "VT");
            Object dataInfo = queryData.getInfo();
            return success(dfr.getUpdateTime(), new QueryDataVo(dfr.getId(), dataInfo, tel));
        } else {
            return warn(dfr.getUpdateTime(), queryData.getMsg());
        }
    }

    public QueryData streamReport(DtFinalResult dfr, DtQuery query) {
        JSONObject mailData = rc.getCacheObject(STREAM_REPORT + query.getQueryId());
        if (mailData == null) {
            long millis = System.currentTimeMillis();
            String accessToken = rc.getCacheObject(STREAM_REPORT_TOKEN);
            if (StringUtils.isEmpty(accessToken)) {
                String req = "{\"username\": \"19827323877\", \"password\": \"w2quwO(7\"}";
                String rep = dataPost("https://saas.flow.eeiai.cn/saas/open/api/get/token", req, null);
                JSONObject repJson = JSON.parseObject(rep);
                if (repJson.getInteger("code") == 200) {
                    accessToken = repJson.getJSONObject("data").getString("accessToken");
                    rc.setCacheObject(STREAM_REPORT_TOKEN, accessToken, 30, TimeUnit.MINUTES);
                } else {
                    return new QueryData("accessToken获取异常", null);
                }
            }
            String rsaData = "{\"token\":\"" + accessToken + "\",\"getUrl\":\"/open/api/user/many/mail\",\"timeStamp\":" + millis + "}";
            //公钥-加密
            String sign = "";
//            try {
//                sign = AlipaySignature.rsaEncrypt(rsaData, "publicKey1", "UTF-8");
//            } catch (AlipayApiException e) {
//                e.printStackTrace();
//                return new QueryData(e.getErrMsg(), null);
//            }
            String data = "{\"sign\":\"" + sign + "\",\"timeStamp\":\"" + millis + "\",\"userEmail\":{\"userName\":\"" + query.getName() + "\",\"userCard\":\"" + query.getCardNo() + "\",\"dockingSign\":\"" + query.getQueryId() + "\"}}";
            HashMap headList = new HashMap();
            headList.put("Authorization", accessToken);
            String streamRep = dataPost("https://saas.flow.eeiai.cn/saas/open/api/user/many/mail", data, headList);
            JSONObject parseObject = JSON.parseObject(streamRep);

            mailData = parseObject.getJSONObject("data");
            if (parseObject.getInteger("code") == 200) {
                rc.setCacheObject(STREAM_REPORT + query.getQueryId(), mailData.toJSONString(), 1, TimeUnit.DAYS);
            } else {
                return new QueryData(mailData.getString("msg"), null);
            }
            dfr.setInfo(mailData.toJSONString());
            dtFinalResultMapper.updateDtFinalResultInfo(dfr);
        }
        String result = "https://flow-process.eeiai.cn/billProcess?flowId=" + mailData.getString("flowId");
        try {
            result += "&backUrl=" + URLEncoder.encode(back_url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return new QueryData(e.getMessage(), null);
        }
        return new QueryData(result);
    }

    private QueryData thrEleQuery(DtFinalResult dfr, DtQuery query) {
        String[] codes = {"DT00", "DT02"};
        List<DtProduct> dtProducts = dtProductMapper.selectDtProductListByCodes(codes);
        JSONObject info = new JSONObject();
        for (DtProduct dtProduct : dtProducts) {
            JSONObject data = zeWuService.getResult(dfr.getId(), dtProduct, query);
            if ("DT02".equals(dtProduct.getCode())) {
                // 要素查询写入
                String check = null;
                if ("200".equals(data.getString("code"))) {
                    String verification = data.getJSONObject("data").getString("verification");
                    if ("0".equals(verification)) {
                        check = "一致";
                    } else if ("1".equals(verification)) {
                        check = "不一致";
                    } else if ("3".equals(verification)) {
                        check = "核验异常";
                    }
                } else {
                    check = data.getString("message");
                }
                this.setQueryDecision(new QueryDecision(query.getQueryId(), "thrEle", check));
            }
            if ("200".equals(data.getString("code"))) {
                JSONObject data_ = data.getJSONObject("data");
                for (String key : data_.keySet()) {
                    info.put(key, data_.get(key));
                }
            }
        }
        dfr.setInfo(info.toJSONString());
        dtFinalResultMapper.updateDtFinalResultInfo(dfr);
        return new QueryData(info);
    }

    private QueryData generalQuery(DtFinalResult dfr, DtQuery dtQuery) {
        DtProduct product = dtProductMapper.selectDtProductById(dfr.getProductId());
        JSONObject result = zeWuService.getResult(dfr.getId(), product, dtQuery);
        if (result == null) {
            return new QueryData("查询异常");
        } else {
            if ("200".equals(result.getString("code"))) {
                dfr.setInfo(result.toJSONString());
                dtFinalResultMapper.updateDtFinalResultInfo(dfr);
                return new QueryData(result.get("data"));
            }
            return new QueryData(result.getString("message"), null);
        }
    }

    /**
     * 查询查询列表
     *
     * @param queryId 查询列表主键
     * @return 查询列表
     */
    @Override
    public DtQuery selectDtQueryByQueryId(Integer queryId) {
        return dtQueryMapper.selectDtQueryByQueryId(queryId);
    }

    /**
     * 修改查询列表
     *
     * @param DtQuery 查询列表
     * @return 结果
     */
    @Override
    public int updateDtQuery(DtQuery DtQuery) {
        DtQuery.setUpdateTime(DateUtils.getNowDate());
        return dtQueryMapper.updateDtQuery(DtQuery);
    }

    /**
     * 批量删除查询列表
     *
     * @param queryIds 需要删除的查询列表主键
     * @return 结果
     */
    @Override
    public int deleteDtQueryByQueryIds(Integer[] queryIds) {
        return dtQueryMapper.deleteDtQueryByQueryIds(queryIds);
    }
}
